const crypto = require('crypto');

class MessageHandler {
  constructor(db) {
    this.db = db;
  }

  handleMessage(ws, message, clients) {
    const { to, from, content, type, encrypted, messageId } = message;
    const messageType = type || 'text';
    const timestamp = Date.now();

    // Save message to database for both sender and recipient
    // Store as conversation between two peers
    try {
      this.db.saveMessage(to, from, content, messageType, messageId);
    } catch (error) {
      console.error('Error saving message:', error);
    }

    // Find recipient
    const recipient = clients.get(to);

    if (recipient && recipient.ws.readyState === 1) { // WebSocket.OPEN
      // Forward message to recipient
      recipient.ws.send(JSON.stringify({
        type: 'message',
        from: from,
        content: content,
        messageType: messageType,
        encrypted: encrypted || false,
        timestamp: timestamp,
        messageId: messageId
      }));

      // Send delivery confirmation to sender
      ws.send(JSON.stringify({
        type: 'message-delivered',
        to: to,
        timestamp: timestamp,
        messageId: messageId
      }));
    } else {
      // Recipient not online
      ws.send(JSON.stringify({
        type: 'message-failed',
        to: to,
        reason: 'Recipient offline',
        timestamp: timestamp,
        messageId: messageId
      }));
    }
  }

  encryptMessage(message, publicKey) {
    try {
      const encrypted = crypto.publicEncrypt(
        {
          key: publicKey,
          padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
          oaepHash: 'sha256',
        },
        Buffer.from(message)
      );
      return encrypted.toString('base64');
    } catch (error) {
      console.error('Encryption error:', error);
      return null;
    }
  }

  decryptMessage(encryptedMessage, privateKey) {
    try {
      const decrypted = crypto.privateDecrypt(
        {
          key: privateKey,
          padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
          oaepHash: 'sha256',
        },
        Buffer.from(encryptedMessage, 'base64')
      );
      return decrypted.toString();
    } catch (error) {
      console.error('Decryption error:', error);
      return null;
    }
  }

  getMessageHistory(peerId, limit = 100) {
    return this.db.getMessageHistory(peerId, limit);
  }
}

module.exports = MessageHandler;
